# -*- coding: utf-8 -*-
"""
Created on Sat Jun 29 23:21:43 2013

@author: Maxim
"""
import numpy as np
import matplotlib.pyplot as plt
import os
from scipy.interpolate import interp1d

class WTHinges:
    def __init__(self,path=None):
        n = 20
        self.alpha = np.zeros(n)
        self.Hflap = np.zeros(n)
        self.Haileron = np.zeros(n)
        self.V = np.zeros(n)
        self.P = np.zeros(n)
        self.Q = np.zeros(n)
        self.T = np.zeros(n)
        self.M = np.zeros(n)
        self.Re = np.zeros(n)
        self.U       = 0.0
        self.flap    = 0.0
        self.aileron = 0.0
        if not path==None:
            self._read(path)
            self._find_angles(path)
    def _find_angles(self,path):
        idx = path.find('FLP')
        self.flap = float(path[idx+3:idx+6])
        idx = path.find('AIL')
        self.aileron = float(path[idx+3:idx+6])
        idx = path.find('U')
        self.U = float(path[idx+1:idx+3])
        
    def _read(self,path):
        fid = open(path,'rt')
        for i in range(13): fid.readline()
        line = fid.readline()
        while line.strip()!='':
            seg = line.split()
            i = int(seg[0])-1
            self.alpha[i] = float(seg[1])
            self.Hflap[i] = float(seg[2])
            self.Haileron[i] = float(seg[3])
            self.P[i] = float(seg[4])
            self.V[i] = float(seg[5])
            self.Q[i] = float(seg[7])
            self.T[i] = float(seg[8])
            self.M[i] = float(seg[9])
            self.Re[i] = float(seg[10])
            line = fid.readline()
        self._clean_arrays(i+1)
        self._dim_hinge()
        self._splines()
    def _splines(self):
        self.ailAlpha = interp1d(self.alpha,self.Haileron,'cubic')
    def _clean_arrays(self,imax):
        self.alpha = self.alpha[:imax]
        self.Hflap = self.Hflap[:imax]
        self.Haileron = self.Haileron[:imax]
        self.P = self.P[:imax]
        self.V = self.V[:imax]
        self.Q = self.Q[:imax]
        self.T = self.T[:imax]
        self.M = self.M[:imax]
        self.Re = self.Re[:imax]
    def _dim_hinge(self):
        rho = 1.2255
        Sref = 0.48
        cref = 0.36
        q = rho*self.V*self.V / 2.0
        self.HDaileron = self.Haileron * q * Sref * cref
    def sort_at_alpha(self,lb=None,ub=None):
        if lb==None:
            lb = self.alpha[0]
        if ub==None:
            ub = self.alpha[-1]
        idx = list()
        for i,alpha in enumerate(self.alpha):
            if alpha>=lb and alpha<=ub:
                idx.append(i)
        self.alpha = self.alpha[idx]
        self.Haileron = self.Haileron[idx]
        self.HDaileron = self.HDaileron[idx]
        self.Hflap = self.Hflap[idx]
        self.M = self.M[idx]
        self.P = self.P[idx]
        self.V = self.V[idx]
        self.Q = self.Q[idx]
        self.T = self.T[idx]
        self.Re = self.Re[idx]


def find_file_by_number(n,m,wdir=None):
    if wdir==None:
        wdir = r'D:\light aircraft\V05\WT4\Hinge Moment Coeff'
    for r,d,f in os.walk(wdir):
        for files in f:
            if int(files[17:20])==int(n) and int(files[21])==int(m):
                return os.path.join(r,files)

def run_test_01():
    path = find_file_by_number(8,3)
    path2 = find_file_by_number(18,3)
    rslt = WTHinges(path)
    rslt2 = WTHinges(path2)
    print rslt.flap
    print rslt.aileron
    print rslt.U
    rslt.sort_at_alpha(0.0,10.0)
    rslt2.sort_at_alpha(0.0,10.0)
    plt.plot(rslt.alpha,rslt.Haileron,'ro-')
    plt.grid(True)
    plt.hold(True)
    plt.plot(rslt2.alpha,rslt2.Haileron,'bo-')
    plt.ylabel('aileron hinge moment coefficient')
    plt.xlabel('AOA, deg')
    plt.show()

def get_ChAlpha(m,n):
    path = find_file_by_number(m,n)
    rslt = WTHinges(path)
    rslt.sort_at_alpha(0,10)
    ChAlpha = (rslt.Haileron[-1] - rslt.Haileron[0]) / (rslt.alpha[-1] - rslt.alpha[0])
    ChAlphaFit = np.polyfit(rslt.alpha,rslt.Haileron,1)[0]
    return ChAlpha, ChAlphaFit

def get_hinges():
    print '%.4e\t%.4e'%get_ChAlpha(8,1)
    print '%.4e\t%.4e'%get_ChAlpha(8,2)
    print '%.4e\t%.4e'%get_ChAlpha(8,3)
    print '%.4e\t%.4e'%get_ChAlpha(4,1)
    print '%.4e\t%.4e'%get_ChAlpha(4,2)
    print '%.4e\t%.4e'%get_ChAlpha(4,3)
    print '%.4e\t%.4e'%get_ChAlpha(18,1)
    print '%.4e\t%.4e'%get_ChAlpha(18,2)
    print '%.4e\t%.4e'%get_ChAlpha(18,3)

def get_ChDelta(n=3):
    path1 = find_file_by_number(8,n)
    path2 = find_file_by_number(18,n)
    rslt1 = WTHinges(path1)
    rslt2 = WTHinges(path2)
    rslt1.sort_at_alpha(-5,5)
    rslt2.sort_at_alpha(-5,5)
    rslt1._splines()
    rslt2._splines()
    CH1 = rslt1.ailAlpha(0.0)
    CH2 = rslt2.ailAlpha(0.0)
    ChDelta = (CH1 - CH2) / 40.0
    print rslt1.Haileron, rslt2.Haileron
    print ChDelta

if __name__=="__main__":
    run_test_01()
